/**
 * 
 */
package com.jinmei.security.interceptor;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.StrutsStatics;

import com.jinmei.model.User;
import com.jinmei.utils.JinmeiConsts;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

/**
 * @author richard
 *
 */
public class AdminAuthenticationInterceptor extends AbstractInterceptor {

	private static final long serialVersionUID = -8849209500061588960L;
	
	private static final Logger log = Logger.getLogger(AdminAuthenticationInterceptor.class);

	@Override  
    public String intercept(ActionInvocation invocation) throws Exception {  
        HttpServletRequest request =
        		(HttpServletRequest) invocation.getInvocationContext().get(StrutsStatics.HTTP_REQUEST);
        // continue when action is login
        if (request.getRequestURI().contains("login")) {
        	return invocation.invoke(); 
        }
        
        Map<String, Object> session = ActionContext.getContext().getSession();
        User user = (User) session.get(JinmeiConsts.USER);
        if (user == null) {
        	// redirect to login page if user not found in session  
//            ActionSupport action = (ActionSupport) invocation.getAction();  
//            action.addActionMessage("not logged in or session time out.Please login!");  
            request.setAttribute("msg", "未登录或者Session过期.请重新登陆!");
            log.info("user not found in session.");
            return Action.LOGIN; 
        }
        
        String serverSessionid = user.getSessionid();
        String clientSessionId = request.getParameter(JinmeiConsts.USER_SESSIONID);
        if (!StringUtils.equals(clientSessionId, serverSessionid)) {  
        	// redirect to login page if sessionid not correct  
//            ActionSupport action = (ActionSupport) invocation.getAction();  
//            action.addActionMessage("not logged in or session time out.Please login!");  
            request.setAttribute("msg", "未登录或者Session过期.请重新登陆!");
            log.info("session time out.");
            return Action.LOGIN;  
        } else {  
        	// continue to invoke action
            return invocation.invoke();  
        }  
    }  

}
